package example.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import example.vo.Link;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

@Log4j
@Service
public class DownloadServiceImpl implements DownloadService {

    public void downloadstring(String firstKey) {
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        try {
            OSSObject ossObject = ossClient.getObject(Link.bucketName, firstKey);
            InputStream inputStream = ossObject.getObjectContent();
            StringBuilder objectContent = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                objectContent.append(line);
            }
            inputStream.close();
            log.info("Object：" + firstKey + "的内容是：" + objectContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ossClient.shutdown();
        log.info("Completed");
    }

    public void downloadfile(String fileKey){
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        ossClient.getObject(new GetObjectRequest(Link.bucketName, fileKey), new File("src/result"));
        ossClient.shutdown();
        log.info("Completed");
    }

    public void downloadthread(String fileKey) throws Throwable {
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        DownloadFileRequest downloadFileRequest = new DownloadFileRequest(Link.bucketName, fileKey); //要下载的文件
        downloadFileRequest.setDownloadFile("src/result");           //下载到该文件
        downloadFileRequest.setPartSize(1024 * 1024);   //分片大小
        downloadFileRequest.setTaskNum(10);                 //分片下载的并发数
        downloadFileRequest.setEnableCheckpoint(true);      //是否开启断点续传功能
        downloadFileRequest.setCheckpointFile("logfiledo");    //记录下载结果，下载完成后会自己删除
        DownloadFileResult downloadRes = ossClient.downloadFile(downloadFileRequest);    // 下载文件。
        downloadRes.getObjectMetadata();                // 下载成功时，会返回文件元信息。
        ossClient.shutdown();
        log.info("Completed");
    }




}
